package com.t.bricks.bussiness.db.dao.workovertimeapply.impl;

import java.util.Arrays;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.t.bricks.bussiness.db.dao.workovertimeapply.WorkOvertimeApplyDao;
import com.t.bricks.bussiness.db.entity.workovertimeapply.WorkOvertimeApply;
import com.t.bricks.bussiness.db.mapper.workovertimeapply.WorkOvertimeApplyMapper;
import com.t.bricks.model.Log;
import com.t.bricks.model.MsgEmity;

@Repository
public class WorkOvertimeApplyDaoImpl implements WorkOvertimeApplyDao<WorkOvertimeApply> {
	
	@Autowired
	private WorkOvertimeApplyMapper workOvertimeApplyMapper;

	/**
	 * 修改状态
	 * @param sId 编号
	 * @param iState 状态值
	 * @param iVersion 记录版本号
	 * @param sMemo 备注
	 * @return MsgEmity 返回执行情况
	 */
	@Override
	public MsgEmity changeState(String sId, Integer iState, Integer iVersion, String sMemo) {
		try {
			int i = workOvertimeApplyMapper.changeState(sId, iState, iVersion, sMemo);
			if (i < 1) {
				MsgEmity me = this.getValueByFieldName(sId, Arrays.asList("iState", "iVersion"), true);//如果影响数小于1,则检查数据
				if (!me.isSuccess()) {
					return me.appendDataCode(100);
				}
				
				Map<String, Object> map = me.getData();
				if (null == map) {
					return new MsgEmity(false, "没有找到对应数据！", 7001);//删除影响数失败,但数据也不存在则视为成功
				}
				
				if (iVersion != Integer.valueOf(map.get("iVersion").toString()).intValue()) {
					return new MsgEmity(false, "更新状态失败，系统中的数据可能已经被更新！", 7002);
				}
				
				if (iState >= 0 && iState < Integer.valueOf(map.get("iState").toString()).intValue()) {
					return new MsgEmity(false, "更新状态失败，状态禁止逆操作！", 7003);
				}

				Log.error("更新状态未能得到预期影响值(预期1):", i);
				return new MsgEmity(false, "更新状态数据失败！", 7004);
			}
		} catch (Exception e) {
			Log.error("更新状态时发生异常:", e.getMessage());
			return new MsgEmity(false, "更新状态失败！", 7005);
		}
		
		return new MsgEmity(true, "更新状态成功！", 7999);
	}

}
